package server

import (
	"bufio"
	"log"
	"net"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// 服务器收到连接, 监听连接

type Server struct {
	sessions map[string]*Session
}

func NewServer() *Server {
	return &Server{
		sessions: map[string]*Session{},
	}
}

func (tis *Server) Serve() {
	r := gin.Default()
	r.GET("/websocket/:puId", func(c *gin.Context) {
		puId := c.Param("puId")

		var upgrade = websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		}

		wsConn, err := upgrade.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			return
		}

		log.Println("new websocket connection, ", puId)
		session := NewSession(puId, wsConn)
		tis.sessions[puId] = session

		session.Handle()
	})

	go tis.ListenTCP()

	_ = r.Run(":5566")
}

func (tis *Server) ListenTCP() {
	listen, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: 5567})
	if err != nil {
		return
	}

	for {
		conn, err := listen.AcceptTCP()
		if err != nil {
			break
		}

		log.Println("收到连接")
		go tis.handleTCP(conn)
	}
}

func (tis *Server) handleTCP(netConn *net.TCPConn) {
	defer func() {
		_ = netConn.Close()

	}()

	r := bufio.NewReader(netConn)
	line, _, err := r.ReadLine()
	if err != nil {
		log.Println(err)
		return
	}

	puId := string(line)

	session, ok := tis.sessions[puId]
	if !ok {
		return
	}

	conn := session.NewTCP(netConn, puId)
	conn.Open()

	// 读取数据循环
	conn.readLoop(r)

	conn.Close()
	session.DeleteTCP(conn.connId)
}
